package com.gzc.just.play.last.war.sceneserver.connection;

import com.gzc.just.play.last.war.common.connection.NacosAwareConnector;
import com.gzc.just.play.last.war.common.connection.ServerConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.util.HashMap;
import java.util.Map;

/**
 * SceneServer connector
 * Responsible for establishing and maintaining connections from SceneServer to other servers
 * 支持Nacos服务发现和静态配置两种模式
 */
@Component
public class SceneServerConnector extends NacosAwareConnector {
    
    private static final Logger log = LoggerFactory.getLogger(SceneServerConnector.class);
    
    @Value("${central.server.host:127.0.0.1}")
    private String centralServerHost;
    
    @Value("${central.server.port:6001}")
    private int centralServerPort;
    
    @PostConstruct
    public void init() {
        log.info("Initializing SceneServer connections...");
        initializeConnections();
        log.info("SceneServer connections initialization completed");
    }
    
    @Override
    protected Map<String, ServerConnectionManager.ServerType> getDependencies() {
        Map<String, ServerConnectionManager.ServerType> dependencies = new HashMap<>();
        // Nacos服务名与ServerType的映射
        dependencies.put("central-server", ServerConnectionManager.ServerType.CENTRAL_SERVER);
        return dependencies;
    }
    
    @Override
    protected void initializeWithStaticConfig() {
        log.info("Initializing with static configuration (Nacos disabled)");
        
        // Register server configuration
        connectionManager.registerServerConfig(
                ServerConnectionManager.ServerType.CENTRAL_SERVER,
                new ServerConnectionManager.ServerConfig(centralServerHost, centralServerPort)
        );
        
        // Establish connections
        establishConnections();
        
        // Start heartbeat detection
        connectionManager.startHeartbeat();
    }
    
    /**
     * Establish server connections (静态配置模式)
     */
    private void establishConnections() {
        try {
            // Connect to central server
            connectionManager.establishConnection(
                ServerConnectionManager.ServerType.CENTRAL_SERVER
            );
            
            log.info("Successfully connected to Central Server");
        } catch (Exception e) {
            log.error("Failed to establish connection to Central Server", e);
        }
    }
    
    @PreDestroy
    public void shutdown() {
        log.info("Shutting down SceneServer connections...");
        shutdownConnections();
        log.info("SceneServer connections shut down");
    }
}